// pages/index/index.js
var that,
  request = require('../../common/request.js');
Page({
  data: {
    article: '',
    list:[]
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    this.refresh = function (devices) {
      if (devices != null && '' != devices) {
        var deviceList = devices.split(',');
        var deviceObjList = [deviceList.length];
        for (var i = 0; i < deviceList.length; i++) {
          var temp = deviceList[i].split('|');
          deviceObjList[i] = new Object();
          deviceObjList[i].title = temp[0];
          deviceObjList[i].sk = temp[1];
        }
        that.setData({
          list: deviceObjList
        });
      } else {
        that.setData({
          list: []
        })
      }
    }

    //检查是否存在新版本
    wx.getUpdateManager().onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log("是否有新版本：" + res.hasUpdate);
      if (res.hasUpdate) {//如果有新版本

        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateReady(function () {//当新版本下载完成，会进行回调
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，单击确定重启应用',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.getUpdateManager().applyUpdate();
              }
            }
          })

        })

        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateFailed(function () {//当新版本下载失败，会进行回调
          wx.showModal({
            title: '提示',
            content: '检查到有新版本，但下载失败，请检查网络设置',
            showCancel: false,
          })
        })
      }
    });
    
  },
  onReady: function () {
    // 页面渲染完成
    var devices = wx.getStorageSync("devices"); 
    var frun = wx.getStorageSync("first_run");
    if(frun == null || '' == frun) {
      wx.showModal({
        title: '帮助',
        content: '1.点击“添加设备”，扫描iotechn用户后台的二维码可获取设备\n\n2.长按已经添加的设备可移除设备!',
        cancelText: '没看',
        confirmText: '看了',
        success: function(res) {
          if (res.confirm) {
            wx.setStorageSync("first_run", 'false');
          }
        }
      })
    }
    this.refresh(devices);
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function () {
    return {
      title: 'iotechn控制器',
      path: '/pages/index/index',
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },
  touchStart: function (e) {
    this.startTime = e.timeStamp;
  },

  clickUp: function (e) {
    this.endTime = e.timeStamp;
    var delta = this.endTime - this.startTime;
    if (delta < 350) {
      //click
      var sk = e.currentTarget.dataset.sk;
      wx.navigateTo({
        url: 'detail/detail?sk=' + sk
      });
    }else {
      //press
      wx.showModal({
        title: '提示',
        content: '确认要移除此设备吗？',
        success: function(res) {
          if (res.confirm) {
            var sk = e.currentTarget.dataset.sk;
            var devices = wx.getStorageSync("devices");
            if (devices != null && '' != devices) {
              var deviceList = devices.split(',');
              var deviceObjList = [deviceList.length];
              for (var i = 0; i < deviceList.length; i++) {
                var temp = deviceList[i].split('|');
                deviceObjList[i] = new Object();
                deviceObjList[i].title = temp[0];
                deviceObjList[i].sk = temp[1];
              }
              //重新build
              var newDevices = '';
              var first = true;
              for (var i = 0; i < deviceList.length; i++) {
                if (deviceObjList[i].sk != sk) {
                  if (first) {
                    first = false;
                  } else {
                    newDevices = newDevices + ",";
                  }
                  newDevices = deviceObjList[i].title + "|" + sk;
                }
              }
              wx.setStorageSync("devices", newDevices);
              that.refresh(newDevices);
            }
          } 
        }
      })
    }
  },

  clickClear: function (e) {
    wx.setStorageSync("devices", "");
  },

  clickScan: function (e) {
    wx.scanCode({
      success: (codeRes) => {
        //发送一个请求，查询设备是否存在
        console.log(codeRes.result);
        wx.request({
          url: 'https://open.iotechn.com/m.api',
          data: {
            _gp: "device", _mt: "getDeviceBySecretKey", secretKey: codeRes.result
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function(res) {
            var data = res.data;
            if(data.code == 200) {
              var devices = wx.getStorageSync("devices");
              if(devices.indexOf(codeRes.result) == -1){
                if (devices == null || '' == devices) {
                  devices = (data.result.title == '' ? data.result.name : data.result.title) + "|" + codeRes.result;
                } else {
                  devices = devices + ',' + (data.result.title == '' ? data.result.name : data.result.title) + "|" + codeRes.result;
                }
                wx.setStorageSync("devices", devices);
                that.refresh(devices);
              }else {
                wx.showToast({
                  title: '重复添加',
                })
              }
              
            } else {
              wx.showToast({
                title: "error:" + data.code
              })
            }
          }
        })
        
      }
    })
  }
})
